package com.neu.flashmall.product.service.impl;

import com.neu.common.entity.Tree;
import com.neu.flashmall.product.entity.PmsCategory;
import com.neu.flashmall.product.feign.ThirdPartyFeignService;
import com.neu.flashmall.product.entity.PmsSpuInfo;
import com.neu.flashmall.product.mapper.PmsCategoryMapper;
import com.neu.flashmall.product.service.PmsCategoryService;
import com.neu.flashmall.product.vo.HeaderCategoryVo;
import com.neu.flashmall.product.vo.PmsCategoryVo;
import com.neu.flashmall.product.vo.PmsCategoryMallVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class PmsCategoryServiceImpl implements PmsCategoryService {
    @Resource
    private PmsCategoryMapper pmsCategoryMapper;

    @Resource
    private ThirdPartyFeignService thirdPartyFeignService;

    /**
     * 构建PmsCategoryVo
     * @return
     */
    @Override
    public PmsCategoryVo getPmsCategoryVo() {
        List<PmsCategory> pmsCategoryLevel3 = pmsCategoryMapper.selectByLevel(3);
        List<PmsCategoryVo.PmsCategoryItem> pmsCategoryItemLevel3 = this.getPmsCategoryItemList(pmsCategoryLevel3);

        List<PmsCategory> pmsCategoryLevel2 = pmsCategoryMapper.selectByLevel(2);
        List<PmsCategoryVo.PmsCategoryItem> pmsCategoryItemLevel2 = this.getPmsCategoryItemList(pmsCategoryLevel2);

        List<PmsCategory> pmsCategoryLevel1 = pmsCategoryMapper.selectByLevel(1);
        List<PmsCategoryVo.PmsCategoryItem> pmsCategoryItemLevel1 = this.getPmsCategoryItemList(pmsCategoryLevel1);


        try {
            this.findChildren(pmsCategoryItemLevel2,pmsCategoryItemLevel3);
            this.findChildren(pmsCategoryItemLevel1,pmsCategoryItemLevel2);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

        PmsCategoryVo result = new PmsCategoryVo();
        result.setData(pmsCategoryItemLevel1);
        return result;
    }

    @Override
    public String addPmsCategoryLevel1(PmsCategory pmsCategory) {
        PmsCategory has = this.pmsCategoryMapper.selectByName(pmsCategory.getName());
        if(has != null){
            return "商品类别名称已存在";
        }
        int result = this.pmsCategoryMapper.insert(pmsCategory);
        if(result >0) return "添加商品类别成功";
        return "未知原因错误";
    }

    @Override
    public String updatePmsCategory(PmsCategory pmsCategory) {
        PmsCategory has = this.pmsCategoryMapper.selectByName(pmsCategory.getName());
        if(has != null && !has.getId().equals(pmsCategory.getId())){
            return "商品类别名已经存在";
        }
        int result = this.pmsCategoryMapper.updateByPrimaryKeySelective(pmsCategory);
        if(result > 0){
            return "更新类别信息成功";
        }
        return "未知原因错误";
    }

    @Override
    public String deletePmsCategory(Long id) {
        List<Long> idList = this.pmsCategoryMapper.selectAllSonById(id);
        idList.add(id);
        int result = this.pmsCategoryMapper.deleteAllById(idList);
        if(result > 0){
            this.thirdPartyFeignService.deleteCategoryIcon(String.valueOf(id));
            return "删除类别成功";
        }
        return "删除失败，未知错误";
    }

    @Override
    public List<PmsCategory> getAllThirdCategory() {
        List<PmsCategory> pmsCategoryLevel3 = pmsCategoryMapper.selectByLevel(3);
        return pmsCategoryLevel3;
    }

    @Override
    public String updateIcon(PmsCategory pmsCategory) {
        int result = this.pmsCategoryMapper.updateByPrimaryKeySelective(pmsCategory);
        if(result > 0) return "更新URL成功";
        return "数据库异常";
    }

    @Override
    public PmsCategoryMallVo makeUpPmsCategoryMallVo(Long id) {
        PmsCategory father = pmsCategoryMapper.selectByPrimaryKey(id);
        List<PmsCategory> child = pmsCategoryMapper.selectByParentId(id);
        PmsCategoryMallVo pmsCategoryMallVo = new PmsCategoryMallVo();
        pmsCategoryMallVo.setFather(father);
        pmsCategoryMallVo.setChildren(toChildrenItem(child));
        return pmsCategoryMallVo;
    }

    @Override
    public HeaderCategoryVo makeUpHeaderCategoryVo(int quantity,int childrenQuantity) {
        List<PmsCategory> secondLevel = this.pmsCategoryMapper.selectQuantitySecondLevel(quantity);
        List<HeaderCategoryVo.PmsCategoryItem> list = new ArrayList<>();
        HeaderCategoryVo headerCategoryVo = new HeaderCategoryVo();
        for(PmsCategory pmsCategory : secondLevel){
            HeaderCategoryVo.PmsCategoryItem item = new HeaderCategoryVo.PmsCategoryItem();
            List<PmsCategory> children = this.pmsCategoryMapper.selectQuantityByParentId(pmsCategory.getId(),childrenQuantity);
            item.setFather(pmsCategory);
            item.setChildren(children);
            list.add(item);
        }
        headerCategoryVo.setSecondLevel(list);
        return headerCategoryVo;
    }

    @Override
    public List<PmsCategory> getThirdCategory() {
        return this.pmsCategoryMapper.selectByLevel(3);
    }

    @Override
    public Tree getCategoryTree() {
        List<PmsCategory> firstLevel = this.pmsCategoryMapper.selectByLevel(1);
        List<Tree.TreeNode> firstLevelTree = createTreeNodeList(firstLevel);
        List<PmsCategory> secondLevel = this.pmsCategoryMapper.selectByLevel(2);
        List<Tree.TreeNode> secondLevelTree = createTreeNodeList(secondLevel);
        List<PmsCategory> thirdLevel = this.pmsCategoryMapper.selectByLevel(3);
        List<Tree.TreeNode> thirdLevelTree = createTreeNodeList(thirdLevel);
        makeUpTreeNodeChildren(secondLevelTree,thirdLevelTree,1);
        makeUpTreeNodeChildren(firstLevelTree,secondLevelTree,1);
        Tree tree = new Tree();
        tree.setData(firstLevelTree);
        return tree;
    }

    private List<Tree.TreeNode> createTreeNodeList(List<PmsCategory> source){
        List<Tree.TreeNode> result = new ArrayList<>();
        for (PmsCategory item : source){
            Tree.TreeNode node = new Tree.TreeNode();
            node.setId(item.getId());
            node.setName(item.getName());
            node.setParent(item.getParentId());
            result.add(node);
        }
        return result;
    }

    /**
     *
     * @param father
     * @param son
     * @param model
     * model = 1的时候，去除没有子项的父项
     */
    private void makeUpTreeNodeChildren(List<Tree.TreeNode> father,List<Tree.TreeNode> son,int model){
        Iterator<Tree.TreeNode> it1 = father.iterator();
        while(it1.hasNext()){
            Tree.TreeNode f = it1.next();
            List<Tree.TreeNode> children = new ArrayList<>();
            Iterator<Tree.TreeNode> it2 = son.iterator();
            while (it2.hasNext()){
                Tree.TreeNode s = it2.next();
                if(s.getParent().equals(f.getId())){
                    children.add(s);
                    it2.remove();
                }
            }
            f.setChildren(children);
            if(model == 1){
                if(children.isEmpty()){
                    it1.remove();
                }
            }
        }
    }


    private List<PmsCategoryMallVo.PmsCategoryChildrenItem> toChildrenItem(List<PmsCategory> pmsCategories){
        List<PmsCategoryMallVo.PmsCategoryChildrenItem> list = new ArrayList<>();
        for (PmsCategory pmsCategory:pmsCategories
             ) {
            PmsCategoryMallVo.PmsCategoryChildrenItem childrenItem = new PmsCategoryMallVo.PmsCategoryChildrenItem();
            childrenItem.setDetail(pmsCategory);
            childrenItem.setSpuInfoList(getSpuInfoByCategoryId(pmsCategory.getId()));
            list.add(childrenItem);
        }
        return list;
    }

    private List<PmsSpuInfo> getSpuInfoByCategoryId(Long id){
        List<PmsSpuInfo> list = new ArrayList<>();
        return list;
    }

    /**
     * 构建PmsCategoryItemList
     * @param pmsCategories
     * @return
     */
    private List<PmsCategoryVo.PmsCategoryItem> getPmsCategoryItemList(List<PmsCategory> pmsCategories){
        List<PmsCategoryVo.PmsCategoryItem> pmsCategoryItemList = new ArrayList<>();
        for(PmsCategory i : pmsCategories){
            PmsCategoryVo.PmsCategoryItem newItem = new PmsCategoryVo.PmsCategoryItem();
            newItem.setDetail(i);
            newItem.setShow(i.getShowStatus() == 1?true:false);
            newItem.setName(i.getName());
            newItem.setId(i.getId());
            pmsCategoryItemList.add(newItem);
        }
        return pmsCategoryItemList;
    }

    private void findChildren(List<PmsCategoryVo.PmsCategoryItem> father, List<PmsCategoryVo.PmsCategoryItem> son) throws CloneNotSupportedException {
        Iterator<PmsCategoryVo.PmsCategoryItem> iterator1 = father.iterator();


        while(iterator1.hasNext()){
            PmsCategoryVo.PmsCategoryItem itemFather = iterator1.next();
            ArrayList<PmsCategoryVo.PmsCategoryItem> it_son = new ArrayList<>();
            Iterator<PmsCategoryVo.PmsCategoryItem> iterator2 = son.iterator();
            while(iterator2.hasNext()){
                PmsCategoryVo.PmsCategoryItem nowItem = iterator2.next();
                if(nowItem.getDetail().getParentId().equals(itemFather.getId())){
                    /**
                     * 这里用到了实体类深度克隆，来将克隆对象添加到新的list中，
                     * 因为我们在后面要在原来的list中删除对象，如果不克隆，到时候删除原来list中的对象后
                     * 我们新list的对象就没有了
                     */
                    it_son.add((PmsCategoryVo.PmsCategoryItem) nowItem.clone());
                    iterator2.remove();
                }
            }
            itemFather.setChildren(it_son);
        }
    }
}
